﻿using System.Collections.Generic;
using System.Linq;

namespace Cms.Domain
{
    public class PluginTemplate
    {
        private IList<PluginTemplateLiteral> _literals;
        private Site _site;
        private SourceCode _sourceCode;

        public PluginTemplate()
        {
            _literals = new List<PluginTemplateLiteral>();
        }
        
        public virtual int ID { get; set; }
        
        public virtual string Name { get; set; }

        public virtual string Description { get; set; }
        
        public virtual SourceCode SourceCode
        {
            get { return _sourceCode; }
            set { _sourceCode = value; }
        }

        public virtual Plugin Plugin { get; set; }

        public virtual Site Site
        {
            get { return _site; }
            set { _site = value; }
        }

        public virtual IList<PluginTemplateLiteral> Literals
        {
            get { return _literals; }
            set { _literals = value; }
        }
        
        public virtual string GetCode()
        {
            return _sourceCode != null ? _sourceCode.CurrentVersion.Code : string.Empty;
        }

        public virtual void SetCode(string code, Administrator editedBy)
        {
            if (_sourceCode == null)
            {
                _sourceCode = new SourceCode();
                _sourceCode.Site = _site;
            }
            _sourceCode.AddVersion(code, editedBy);
        }
        
        public virtual PluginTemplateLiteral GetLiteral(string controlID)
        {
            IEnumerable<PluginTemplateLiteral> literals = from l in _literals
                                                          where l.ControlID.ToLower() == controlID.ToLower()
                                                          select l;
            return literals.Count() == 1 ? literals.First() : null;
        }
        
        public virtual PluginTemplateLiteral GetLiteral(int id)
        {
            IEnumerable<PluginTemplateLiteral> literals = from l in _literals where l.ID == id select l;
            return literals.Count() == 1 ? literals.First() : null;
        }
    }
}